﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace CS.Caching
{
    /// <summary>
    /// 缓存工厂
    /// <remarks>
    /// 创建类型<see cref="CS.Caching.FuncCache"/>的缓存实例
    /// </remarks>
    /// </summary>
    public static class CacheFactory
    {

        static CacheFactory()
        {
            timer = new Timer(ClearWork,null,5000,5000);//每5秒钟调用一次清扫
        }

        private static readonly Timer timer;

        private static readonly List<Action> eraser = new List<Action>();
        /// <summary>
        /// 清除工作
        /// </summary>
        /// <param name="o"></param>
        static void ClearWork(object o)
        {
            foreach (var func in eraser)
            {
                func.Invoke();
            }
        }

        /// <summary>
        /// 创建主动模式缓存
        /// <remarks>请将结果实例静态存储，否则无法缓存</remarks>
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <returns></returns>
        public static FuncCache<TKey, TValue> Create<TKey, TValue>(string cacheName) where TValue:class 
        {
            return Create<TKey,TValue>(cacheName,30, 8, CacheExpireMode.ByCreateTime);
        }

        /// <summary>
        /// 创建缓存
        /// <remarks>请将结果实例静态存储，否则无法缓存</remarks>
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="cacheName"></param>
        /// <param name="expireMode"></param>
        /// <returns></returns>
        public static FuncCache<TKey, TValue> Create<TKey, TValue>(string cacheName, CacheExpireMode expireMode) where TValue : class 
        {
            return Create<TKey,TValue>(cacheName,30, 8, expireMode);
        }

        /// <summary>
        /// 创建缓存
        /// <remarks>请将结果实例静态存储，否则无法缓存</remarks>
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="cacheName">缓存名称</param>
        /// <param name="lifeTime">有效期，秒</param>
        /// <param name="maxCache">最大缓存数量</param>
        /// <param name="expireMode">缓存模式</param>
        /// <returns></returns>
        public static FuncCache<TKey, TValue> Create<TKey, TValue>(string cacheName, int lifeTime, int maxCache, CacheExpireMode expireMode) where TValue : class 
        {
            var cache = new FuncCache<TKey, TValue>(lifeTime,maxCache,expireMode) {CacheName = cacheName};
            eraser.Add(cache.ClearWorker);
            return cache;
        }



    }


}